﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LuaInterface;
using System;
using System.Runtime.InteropServices;

public class systemfunction
{
    [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
    private static int send(IntPtr luaState)
    {
        string head = LuaDLL.lua_tostring(luaState, 1);
        string body = LuaDLL.lua_tostring(luaState, 2);        
        byte[] headBuf = System.Text.Encoding.UTF8.GetBytes(head);
        byte[] bodyBuf = System.Text.Encoding.UTF8.GetBytes(body);
        byte[] headLenBuf = BitConverter.GetBytes(((short)headBuf.Length));
        byte[] bodyLenBuf = BitConverter.GetBytes(((int)bodyBuf.Length));
        Array.Reverse(headLenBuf);
        Array.Reverse(bodyLenBuf);
        byte[] buffer = new byte[2 + headBuf.Length + 4 + bodyBuf.Length];
        Array.Copy(headLenBuf, buffer, 2);
        Array.Copy(headBuf, 0, buffer, 2, headBuf.Length);
        Array.Copy(bodyLenBuf, 0, buffer, 2 + headBuf.Length, 4);
        Array.Copy(bodyBuf, 0, buffer, 2 + headBuf.Length + 4, bodyLenBuf.Length);

        app.send(buffer);
        return 0;
    }

    [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
    private static int trace(IntPtr luaState)
    {
        string text = LuaDLL.lua_tostring(luaState, 1);
        Debug.Log(text);
        return 0;
    }

    public static void registerFunc()
    {
        List<LuaMethod> systemLib = new List<LuaMethod>();
        systemLib.Add(new LuaMethod("trace", systemfunction.trace));
        systemLib.Add(new LuaMethod("send", systemfunction.send));
        LuaHelper.getLuaModule().registerLib("System", systemLib.ToArray());
    }
}
